package demo.android.myapplication.demos.views

import android.content.Context
import android.graphics.*
import android.os.Build
import android.util.AttributeSet
import android.view.View
import android.widget.Toast
import androidx.annotation.RequiresApi
import cn.android.basic.*
import demo.android.myapplication.R

/**
 * <br>createBy Gw
 * <br>createTime: 2021/7/7 16:22
 * Xfermode
 */
class AvatarView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val avatar: Bitmap by lazy {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeResource(resources, R.mipmap.pujing_avatar, options)
        options.inJustDecodeBounds = false

        // 通过 inDensity 和 inTargetDensity 可以 decode 出想要的图片大小
        // 如:
        // 图片: 400 * 400
        // 目标: 40 * 40
        // inDensity = 400
        // inTargetDensity = 40
        // Bitmap bitmap = BitmapFactory.decodeResource(xxx, xxx, xxx)
        // 则 bitmap.width 等于 40
        options.inDensity = options.outWidth
        options.inTargetDensity = (realRight - realLeft).toInt()

        return@lazy BitmapFactory.decodeResource(resources, R.mipmap.pujing_avatar, options)
    }
    private val xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
    private val rect = RectF()

    init {
        setLayerType(LAYER_TYPE_HARDWARE, null)
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        rect.set(realLeft, realTop, realRight, realBottom)
        val tag = canvas.save()
        canvas.drawCircle(centerX, centerY, (realRight - realLeft) / 2, paint)
        paint.xfermode = xfermode
        canvas.drawBitmap(avatar, realLeft, realTop, paint)
        canvas.restoreToCount(tag)
        paint.xfermode = null
    }
}